import java.util.Stack;

/**
 * 最小栈
 * 能在常数时间内检索到最小元素的栈
 */
public class MinStack {
    Stack<Integer> stack;
    Stack<Integer> minStack;
    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    /**
     * 入栈
     * @param val
     */
    public void push(int val) {
        stack.push(val);
        if (minStack.empty()){
            minStack.push(val);
        }else {
            if (minStack.peek() >= val){
                minStack.push(val);
            }
        }
    }

    /**
     * 出栈
     */
    public void pop() {
        if (stack.empty()){
            return;
        }else {
            int val = stack.pop();
            int minVal = minStack.peek();
            if (val == minVal){ // stack.peek() == minStack.peek()->错误写法
                minStack.pop();
            }
        }
    }

    /**
     * 查看栈顶元素
     * @return
     */
    public int top() {
        if (stack.empty()){
            return -1;
        }
        return stack.peek();
    }

    /**
     * 获取最小元素
     * @return
     */
    public int getMin() {
        if (minStack.empty()){
            return -1;
        }
        return minStack.peek();
    }
}
